package com.quartz.config;

import com.quartz.listeners.QuartzJobListeners;
import com.quartz.listeners.QuartzTriggerListeners;
import org.quartz.ListenerManager;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import static org.quartz.impl.matchers.EverythingMatcher.allJobs;
import static org.quartz.impl.matchers.EverythingMatcher.allTriggers;

/**
 *
 *  定时quartz定时任务配置
 * @author HeWei123
 */
@Configuration
public class QuartzConfig {

   @Autowired
   private JobFactory jobFactory;

    /**
     * 配置SchedulerFactoryBean
     *
     * 将一个方法产生为Bean并交给Spring容器管理
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) throws IOException {
        // Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 设置自定义Job Factory，用于Spring管理Job bean
        factory.setJobFactory(jobFactory);
        // 用于quartz集群,QuartzScheduler 启动时更新己存在的Job
        factory.setOverwriteExistingJobs(true);
        factory.setQuartzProperties(quartzProperties());
        factory.setDataSource(dataSource);
        factory.setConfigLocation(new ClassPathResource("quartz.properties"));
        //
        Map<String,Object> map = new HashMap<>();
        map.put("factory","1");
        factory.setSchedulerContextAsMap(map);
        //延长启动
        factory.setStartupDelay(10);
        return factory;
    }


    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
        //在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }


    /**
     * 创建schedule
     * @return
     * @throws SchedulerException
     */
    @Bean(name = "scheduler")
    public Scheduler scheduler(DataSource dataSource) throws SchedulerException, IOException {
        Scheduler scheduler = schedulerFactoryBean(dataSource).getScheduler();
        ListenerManager listenerManager = scheduler.getListenerManager();
        listenerManager.addJobListener(new QuartzJobListeners(), allJobs());
        listenerManager.addTriggerListener(new QuartzTriggerListeners(),allTriggers());
        return scheduler;
    }


}
